﻿Imports System
'Imports System.IO
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
'Imports System.Windows.Data
'Imports System.Windows.Media
'Imports System.Windows.Media.Animation
Imports System.Windows.Navigation
Imports System.Text
Imports Microsoft.VisualBasic
Imports System.ComponentModel
Imports System.Data
'Imports System.Threading
'Imports System.Data.Sql

Partial Public Class Window1
	Private WithEvents InitializeBackgroundWorker As BackgroundWorker
	Private WithEvents CheckForUpdatesBackgroundWorker As BackgroundWorker
	Private strVersion As String

	Public Sub New()
		MyBase.New()

		Me.InitializeComponent()

		Try
			Base.win = Windows.Window.GetWindow(Me)

			strVersion = String.Format("{0}.{1:00}.{2}.{3}", My.Application.Info.Version.Major.ToString, My.Application.Info.Version.Minor.ToString, My.Application.Info.Version.Build.ToString, My.Application.Info.Version.Revision.ToString)
			lblProductName.Text = String.Format("{0} {1} Beta", My.Application.Info.ProductName, strVersion)
			LinkUpdates.NavigateUri = New Uri(String.Format("{0}?version={1}&edition={2}", "http://www.bucketsoft.com/data_comparisons/updates/", strVersion, "Express"))
			LinkUpdateAvailable.NavigateUri = New Uri(String.Format("{0}?version={1}&edition={2}", "http://www.bucketsoft.com/data_comparisons/updates/", strVersion, "Express"))

			InitializeBackgroundWorker = New BackgroundWorker
			InitializeBackgroundWorker.RunWorkerAsync()

			CheckForUpdatesBackgroundWorker = New BackgroundWorker
			CheckForUpdatesBackgroundWorker.WorkerSupportsCancellation = True
			CheckForUpdatesBackgroundWorker.RunWorkerAsync()
		Catch ex As Exception
			Base.WriteToConsole(ex.ToString)
		End Try

		'Dim sqlinstances() As SqlServerInfo = SqlServerInfo.Seek

		'For Each sqlinstance As SqlServerInfo In sqlinstances
		'	Base.WriteToConsole(Me, String.Format("{0}\{1}", sqlinstance.ServerName, sqlinstance.InstanceName))
		'Next
	End Sub

	Private Sub InitializeBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles InitializeBackgroundWorker.DoWork
		Base.GetConnections()
		Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Render, New LoadStepCallback(AddressOf LoadStep), 1)

		' Insert code required on object creation below this point.
		ConnectionA.DB = CChar("A")
		ConnectionB.DB = CChar("B")
		DatabaseA.DB = CChar("A")
		DatabaseB.DB = CChar("B")

		Dim dpdIsConnected As DependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(Connection.IsConnectedProperty, GetType(Connection))
		dpdIsConnected.AddValueChanged(ConnectionA, AddressOf OnConnected)
		dpdIsConnected.AddValueChanged(ConnectionB, AddressOf OnConnected)

		Dim dpdIsReady As DependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(Database.IsReadyProperty, GetType(Database))
		dpdIsReady.AddValueChanged(DatabaseA, AddressOf OnReady)
		dpdIsReady.AddValueChanged(DatabaseB, AddressOf OnReady)

		Dim dpdIsComparing As DependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(Results.IsComparingProperty, GetType(Results))
		dpdIsComparing.AddValueChanged(myResults, AddressOf OnComparing)

		e.Result = True
	End Sub

	Private Sub CheckForUpdatesBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles CheckForUpdatesBackgroundWorker.DoWork
		e.Result = CheckForUpdates()
	End Sub

	Private Sub CheckForUpdatesBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles CheckForUpdatesBackgroundWorker.RunWorkerCompleted
		If TypeOf e.Result Is Boolean AndAlso DirectCast(e.Result, Boolean) Then
			TextUpdateAvailable.Visibility = Windows.Visibility.Visible
		Else
			TextUpdateAvailable.Visibility = Windows.Visibility.Hidden
		End If
	End Sub

	Private Function CheckForUpdates() As Boolean
		Try
			Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Render, New Base.WriteToConsoleCallback(AddressOf Base.WriteToConsole), "Checking for updates from BucketSoft...", False)

			Dim wc As New WebClient
			Dim strResult As String = wc.DownloadString(New Uri(String.Format("{0}?returnversion=true&edition={1}", "http://www.bucketsoft.com/data_comparisons/updates/", "Express")))
			If strVersion = strResult Then
				Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Render, New Base.WriteToConsoleCallback(AddressOf Base.WriteToConsole), "You have the latest version.", False)
				Return False
			Else
				Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Render, New Base.WriteToConsoleCallback(AddressOf Base.WriteToConsole), "A new version is available: " & strResult, False)
				Return True
			End If
		Catch ex As Exception
			Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Render, New Base.WriteToConsoleCallback(AddressOf Base.WriteToConsole), "An error occurred while checking for updates:", False)
			Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Render, New Base.WriteToConsoleCallback(AddressOf Base.WriteToConsole), ex.ToString, False)
		End Try

		Return False
	End Function

	Private Sub OnConnected()
		If btnContinue1 IsNot Nothing Then
			If ConnectionA.IsConnected AndAlso ConnectionB.IsConnected Then
				btnContinue1.IsEnabled = True
				btnUseConnectionA.IsEnabled = False
				btnUseConnectionB.IsEnabled = False
				'If Base.sqlConn(CChar("A")).Equals(Base.sqlConn(CChar("B"))) Then
				'  Base.WriteToConsole(Me, "Shared connection mode established")
				'Else
				'  Base.WriteToConsole(Me, "Dual connection mode established")
				'End If
			Else
				btnContinue1.IsEnabled = False
				btnUseConnectionA.IsEnabled = ConnectionA.IsConnected AndAlso Not ConnectionB.IsConnected
				btnUseConnectionB.IsEnabled = ConnectionB.IsConnected AndAlso Not ConnectionA.IsConnected
			End If
		End If
	End Sub

	Private Sub OnReady()
		If btnContinue2 IsNot Nothing Then
			Dim tA As TriState = DatabaseA.IsReady
			Dim tB As TriState = DatabaseB.IsReady

			If Not tA = TriState.False AndAlso Not tB = TriState.False Then
				btnContinue2.IsEnabled = True
				If tA = TriState.True AndAlso tB = TriState.True Then
					'gComparisonReady.Visibility = Windows.Visibility.Visible
					gComparisonProblem.Visibility = Windows.Visibility.Hidden
				Else
					'gComparisonReady.Visibility = Windows.Visibility.Hidden
					gComparisonProblem.Visibility = Windows.Visibility.Visible
				End If
			Else
				btnContinue2.IsEnabled = False
				'gComparisonReady.Visibility = Windows.Visibility.Hidden
				gComparisonProblem.Visibility = Windows.Visibility.Hidden
			End If
		End If
	End Sub

	Private Sub OnComparing()
		btnPrevious2.IsEnabled = Not myResults.IsComparing
	End Sub

	Private Delegate Sub LoadStepCallback(ByVal i As Integer)
	Private Sub LoadStep(ByVal i As Integer)
		Select Case i
			Case 1
				gConnections.Visibility = Windows.Visibility.Visible
				gComparison.Visibility = Windows.Visibility.Hidden
				gResults.Visibility = Windows.Visibility.Hidden
				OnConnected()
			Case 2
				gConnections.Visibility = Windows.Visibility.Hidden
				gComparison.Visibility = Windows.Visibility.Visible
				gResults.Visibility = Windows.Visibility.Hidden
				DatabaseA.LoadDatabase()
				DatabaseB.LoadDatabase()
				cbQuickMode.IsEnabled = (Base.sqlConn(CChar("A")).DataSource = Base.sqlConn(CChar("B")).DataSource)	' Enable the choice for quick mode if the two connections are pointing to the same SQL server instance
				If Not cbQuickMode.IsEnabled Then
					cbStandardMode.IsChecked = True
				End If

				OnReady()
			Case 3
				Base.bQuickMode = cbQuickMode.IsChecked.Value
				myResults.DatabaseNameA = DatabaseA.cmbDatabase.Text
				myResults.DatabaseNameB = DatabaseB.cmbDatabase.Text
				myResults.TableA = DatabaseA.lbTable.SelectedValue.ToString
				myResults.TableB = DatabaseB.lbTable.SelectedValue.ToString
				myResults.KeyA = DatabaseA.lbColumn.SelectedValue.ToString
				myResults.KeyB = DatabaseB.lbColumn.SelectedValue.ToString
				gConnections.Visibility = Windows.Visibility.Hidden
				gComparison.Visibility = Windows.Visibility.Hidden
				gResults.Visibility = Windows.Visibility.Visible
				myResults.StartLoadResults()
		End Select
	End Sub

	Private Sub btnUseConnectionA_Click() Handles btnUseConnectionA.Click
		'If Base.sqlConn(CChar("A")) IsNot Nothing AndAlso Base.sqlConn(CChar("A")).State = ConnectionState.Open Then
			Base.sqlConn(CChar("B")) = Base.sqlConn(CChar("A"))
			ConnectionB.cmbServerType.Text = ConnectionA.cmbServerType.Text
			ConnectionB.cmbServerName.Text = ConnectionA.cmbServerName.Text
			ConnectionB.cmbAuthentication.Text = ConnectionA.cmbAuthentication.Text
			ConnectionB.txtUsername.Text = ConnectionA.txtUsername.Text
			ConnectionB.txtPassword.Password = ConnectionA.txtPassword.Password
			ConnectionB.btnConnect1.Content = "Disconnect"
			ConnectionB.IsConnected = True
		'End If
	End Sub

	Private Sub btnUseConnectionB_Click() Handles btnUseConnectionB.Click
		'If Base.sqlConn(CChar("B")) IsNot Nothing AndAlso Base.sqlConn(CChar("B")).State = ConnectionState.Open Then
			Base.sqlConn(CChar("A")) = Base.sqlConn(CChar("B"))
			ConnectionA.cmbServerType.Text = ConnectionB.cmbServerType.Text
			ConnectionA.cmbServerName.Text = ConnectionB.cmbServerName.Text
			ConnectionA.cmbAuthentication.Text = ConnectionB.cmbAuthentication.Text
			ConnectionA.txtUsername.Text = ConnectionB.txtUsername.Text
			ConnectionA.txtPassword.Password = ConnectionB.txtPassword.Password
			ConnectionA.btnConnect1.Content = "Disconnect"
			ConnectionA.IsConnected = True
		'End If
	End Sub

	Private Sub btnContinue1_Click() Handles btnContinue1.Click
		LoadStep(2)
	End Sub

	Private Sub btnPrevious1_Click() Handles btnPrevious1.Click
		LoadStep(1)
	End Sub

	Private Sub btnContinue2_Click() Handles btnContinue2.Click
		LoadStep(3)
	End Sub

	Private Sub btnPrevious2_Click() Handles btnPrevious2.Click
		LoadStep(2)
	End Sub

	'Private Sub tcMain_Change()
	'  'If tcMain.SelectedIndex = 0 Then
	'  'ElseIf tcMain.SelectedIndex = 1 Then
	'  'End If
	'End Sub

	Private Sub Logo_Clicked() Handles Logo.MouseUp
		OpenURL(New Uri("http://www.bucketsoft.com/").AbsoluteUri)
	End Sub

	Private Sub LinkUpdateAvailable_Clicked(ByVal sender As Object, ByVal e As RequestNavigateEventArgs) Handles LinkUpdateAvailable.RequestNavigate
		OpenURL(e.Uri.AbsoluteUri)
	End Sub

	Private Sub LinkUpdates_Clicked(ByVal sender As Object, ByVal e As RequestNavigateEventArgs) Handles LinkUpdates.RequestNavigate
		OpenURL(e.Uri.AbsoluteUri)
	End Sub

	Private Sub LinkFeedback_Clicked(ByVal sender As Object, ByVal e As RequestNavigateEventArgs) Handles LinkFeedback.RequestNavigate
		OpenURL(e.Uri.AbsoluteUri)
	End Sub

	Private Sub LinkOnlineHelp_Clicked(ByVal sender As Object, ByVal e As RequestNavigateEventArgs) Handles LinkOnlineHelp.RequestNavigate
		OpenURL(e.Uri.AbsoluteUri)
	End Sub

	Private Sub OpenURL(ByVal strURL As String)
		Try
			Dim process As New System.Diagnostics.Process
			process.StartInfo.FileName = strURL
			process.Start()
		Catch
			Base.WriteToConsole("Cannot launch " & strURL & ".  Please type " & strURL & " into your browser instead.", True)
		End Try
	End Sub

	Private Sub Window1_MouseLeftButtonDown() Handles Me.MouseLeftButtonDown
		Me.DragMove()
	End Sub

	Private Sub Window1_Maximize() Handles Me.StateChanged
		If Not Me.WindowState = Windows.WindowState.Maximized Then
			btnMaximize.SetResourceReference(Button.StyleProperty, "MaximizeButton")
			btnMaximize.ToolTip = "Maximize"
		Else
			btnMaximize.SetResourceReference(Button.StyleProperty, "RestoreButton")
			btnMaximize.ToolTip = "Restore"
		End If
	End Sub

	'Private Sub Window1_DoubleClick() Handles Me.MouseDoubleClick
	'	ToggleRestore()
	'End Sub

	Private Sub btnMinimize_Click() Handles btnMinimize.Click
		Me.WindowState = Windows.WindowState.Minimized
	End Sub

	Private Sub btnMaximize_Click() Handles btnMaximize.Click
		ToggleRestore()
	End Sub

	Private Sub DoubleClicked() Handles Me.MouseDoubleClick
		If gHeader.IsMouseOver Then
			ToggleRestore()
		End If
	End Sub

	Private Sub ToggleRestore()
		If Not Me.WindowState = Windows.WindowState.Maximized Then
			Me.WindowState = Windows.WindowState.Maximized
		Else
			Me.WindowState = Windows.WindowState.Normal
		End If
	End Sub

	Private Sub btnClose_Click() Handles btnClose.Click
		Me.Close()
	End Sub

	Private Sub Window_Closing(ByVal sender As Object, ByVal e As CancelEventArgs) Handles Me.Closing
		Try
			If Base.sqlConn(CChar("A")) IsNot Nothing AndAlso Base.sqlConn(CChar("A")).State = ConnectionState.Open Then
				Base.sqlConn(CChar("A")).Close()
			End If

			If Base.sqlConn(CChar("B")) IsNot Nothing AndAlso Base.sqlConn(CChar("B")).State = ConnectionState.Open Then
				Base.sqlConn(CChar("B")).Close()
			End If
		Catch
		Finally
			e.Cancel = False
		End Try
	End Sub

	Private Sub ToggleHelpPopup()
		If b1.IsMouseOver OrElse popup1.IsMouseOver Then
			popup1.IsOpen = True
		Else
			popup1.IsOpen = False
		End If
	End Sub

	Private Sub b1_MouseEnter() Handles b1.MouseEnter
		ToggleHelpPopup()
	End Sub

	Private Sub b1_MouseLeave() Handles b1.MouseLeave
		ToggleHelpPopup()
	End Sub

	Private Sub popup1_MouseLeave() Handles popup1.MouseLeave
		ToggleHelpPopup()
	End Sub

End Class
